package com.ys.timer;

import com.ys.entity.storage.TccFbaBoxUp;
import com.ys.entity.storage.TccFbaPlan;
import com.ys.enume.storage.TccFbaBoxUpEnum;
import com.ys.service.storage.FbaInboundApiService;
import com.ys.vo.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * FBA装箱单定时器
 */
@Controller
public class TimerTccFbaBoxUpDaily {
	private static final Logger logger = LoggerFactory.getLogger(TimerTccFbaBoxUpDaily.class);


	@Autowired
	private FbaInboundApiService fbaInboundApiService;

	//定时更新追踪编号
	@Scheduled(cron = "0 */10 * * * ?")//间隔10分钟执行一次
	public void getFbaTrackNoByApi() {
		try {
			logger.info("***********定时更新追踪编号，开始***********");

			List<TccFbaBoxUp> tccFbaBoxUpList = new TccFbaBoxUp()
					.addLeftJoin("TCC_FbaBoxUpInfo B ON B.BidFbaPlan = A.BidFbaPlan")
					.setBoxState(TccFbaBoxUpEnum.BoxState.YES_PASS.value)//已审核
					.where("B.FbaTrackNo IS NULL OR B.FbaTrackNo = ''")//追踪编号为空
					.queryList();

			if(tccFbaBoxUpList!=null && tccFbaBoxUpList.size()>0){
				//去重
				Map<String, List<TccFbaBoxUp>> groupsByPlanBid = tccFbaBoxUpList.stream().collect(Collectors.groupingBy(e->e.getBidFbaPlan()));
				List<TccFbaBoxUp> groupList = new ArrayList<>();
				//遍历，填入去重的信息
				groupsByPlanBid.forEach((k, v) -> groupList.add(v.get(0)));
				if(groupList.size()>0){
					for(TccFbaBoxUp tccFbaBoxUp:groupList){
						//获取计划单信息
						TccFbaPlan tccFbaPlan = new TccFbaPlan().setBid(tccFbaBoxUp.getBidFbaPlan()).queryFirst();
						//API获取FBA信息
						R apiResByGetFbaInfo = fbaInboundApiService.reSearchShipments(tccFbaBoxUp.getBid(),tccFbaPlan,tccFbaBoxUp.getPlacementOptionId());
						if(apiResByGetFbaInfo.getCode().equals(R.Code.FAILED.value)){
							logger.error("计划单号："+tccFbaBoxUp.getBidFbaPlan()+"定时更新追踪编号出错：",apiResByGetFbaInfo);
						}
					}
				}
			}else {
				logger.info("***********没有需要获取的追踪编号***********");
			}
			logger.info("***********定时更新追踪编号，完成***********");
		}catch (Exception e){
			logger.error("定时更新追踪编号出错：",e.getMessage(),e);
		}
	}








}
